package com.flute.haflute.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.jobbox.common.CloudContext;

public class SerializeHistroyJob {
	private static Logger logger = LoggerFactory
			.getLogger(SerializeHistroyJob.class);

	private String historyJobFile = CloudContext.getRootDir()
			+ "historyjoblist.file";
	
	File file = null;
	static SerializeHistroyJob serializeHistroyJob;

	public static SerializeHistroyJob getInstance() {
		if (null == serializeHistroyJob)
			serializeHistroyJob = new SerializeHistroyJob(null);
		return serializeHistroyJob;
	}

	public SerializeHistroyJob(File file) {
		if (file == null) {
			File newfile = new File(historyJobFile);
			if (!newfile.exists()) {
				try {
					newfile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			this.file = newfile;
		} else {
			this.file = file;
		}

	}

	/**
	 * 序列化保存对象
	 * 
	 * @param obj
	 */
	public void saveSerializeObj(Object obj) {

		try {
			// 1.创建文件输出流,负责将字节写入文件
			FileOutputStream fs = new FileOutputStream(this.file);
			// 2.创建对象输出流,负责将对象转为字节
			ObjectOutputStream os = new ObjectOutputStream(fs);
			// 3.写入对象
			os.writeObject(obj);
			// 4.关闭对象输出流
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解序列化
	 * 
	 * @return
	 */
	public Object uncoilSerializeObj() {
		Object obj = null;
		try {
			// 1.创建文件输入流,负责将文件转为字节
			FileInputStream fi = new FileInputStream(this.file);

			// 2.创建对象输入流,负责将字节写入对象
			ObjectInputStream oi = new ObjectInputStream(fi);
			// 3.读出对象
			obj = oi.readObject();
			// 4.关闭对象输入流
			oi.close();
		} catch (Exception e) {
			logger.error("uncoilSerializeObj error" + e);
		}
		return obj;
	}
}
